<?php
declare(strict_types=1);

namespace app\admin\controller;

use app\common\controller\BaseController;
use app\common\model\Dict as DictModel;
use app\common\model\DictItem as DictItemModel;
use app\common\model\DictItemLang as DictItemLangModel;
use app\common\utils\JsonResponse;
use think\facade\Db;
use think\facade\Request;

class DictItem extends BaseController
{
    /**
     * 处理多语言数据
     * @param array $langs 语言数据数组
     * @return array 处理后的语言数据
     */
    protected function processLangData(array $langs): array
    {
        $result = [];
        
        foreach ($langs as $lang) {
            if (empty($lang['name'])) {
                continue;
            }
            
            if (empty($lang['language_id'])) {
                continue;
            }
            
            $result[] = [
                'language_id' => (int)$lang['language_id'],
                'name' => trim($lang['name']),
                'remark' => !empty($lang['remark']) ? trim($lang['remark']) : ''
            ];
        }
        
        if (empty($result)) {
            throw new \Exception('至少需要一种语言的数据');
        }
        
        return $result;
    }

    /**
     * 获取字典项列表
     * @permission system:dictItem:getList
     */
    public function getList()
    {
        $params = Request::get();
        
        // 检查字典是否存在
        if (empty($params['dict_id'])) {
            return JsonResponse::error('缺少字典ID');
        }
        
        $list = DictItemModel::with(['langs.language'])
            ->where('dict_id', $params['dict_id'])
            ->withSearch(['name', 'status'], $params)
            ->order('sort', 'asc')
            ->select();
            
        return JsonResponse::success([
            'list' => $list
        ]);
    }
    
    /**
     * 添加字典项
     * @permission system:dictItem:doAdd
     */
    public function doAdd()
    {
        $params = Request::post();
        
        Db::startTrans();
        try {
            // 检查字典是否存在
            if (!DictModel::find($params['dict_id'])) {
                throw new \Exception('字典不存在');
            }
            
            // 处理语言数据
            $langs = $this->processLangData($params['langs'] ?? []);
            
            // 创建字典项主表数据
            $dictItem = DictItemModel::create([
                'dict_id' => $params['dict_id'],
                'value' => $params['value'],
                'sort' => $params['sort'] ?? 0,
                'status' => $params['status'] ?? 1
            ]);
            
            // 创建字典项语言数据
            foreach ($langs as $lang) {
                DictItemLangModel::create([
                    'item_id' => $dictItem->item_id,
                    'language_id' => $lang['language_id'],
                    'name' => $lang['name'],
                    'remark' => $lang['remark']
                ]);
            }
            
            Db::commit();
            return JsonResponse::success([], '添加成功');
        } catch (\Exception $e) {
            Db::rollback();
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 编辑字典项
     * @permission system:dictItem:doEdit
     */
    public function doEdit()
    {
        $params = Request::post();
        
        Db::startTrans();
        try {
            // 检查记录是否存在
            $dictItem = DictItemModel::find($params['item_id']);
            if (!$dictItem) {
                throw new \Exception('字典项不存在');
            }
            
            // 处理语言数据
            $langs = $this->processLangData($params['langs'] ?? []);
            
            // 更新主表数据
            $dictItem->save([
                'value' => $params['value'],
                'sort' => $params['sort'] ?? 0,
                'status' => $params['status'] ?? 1
            ]);
            
            // 获取现有的语言数据
            $existingLangs = DictItemLangModel::where('item_id', $params['item_id'])
                ->column('*', 'language_id');
            
            // 更新语言数据
            foreach ($langs as $lang) {
                $langId = $lang['language_id'];
                
                if (isset($existingLangs[$langId])) {
                    // 更新已存在的语言数据
                    DictItemLangModel::update([
                        'name' => $lang['name'],
                        'remark' => $lang['remark'],
                        'item_lang_id' => $existingLangs[$langId]['item_lang_id']
                    ]);
                    unset($existingLangs[$langId]);
                } else {
                    // 创建新的语言数据
                    DictItemLangModel::create([
                        'item_id' => $dictItem->item_id,
                        'language_id' => $langId,
                        'name' => $lang['name'],
                        'remark' => $lang['remark']
                    ]);
                }
            }
            
            Db::commit();
            return JsonResponse::success([], '更新成功');
        } catch (\Exception $e) {
            Db::rollback();
            return JsonResponse::error($e->getMessage());
        }
    }
    
    /**
     * 删除字典项
     * @permission system:dictItem:doDelete
     */
    public function doDelete()
    {
        $itemId = Request::param('item_id');
        
        Db::startTrans();
        try {
            // 检查记录是否存在
            $dictItem = DictItemModel::find($itemId);
            if (!$dictItem) {
                throw new \Exception('字典项不存在');
            }
            
            // 删除主表数据
            $dictItem->delete();
            
            // 删除关联的语言数据
            DictItemLangModel::where('item_id', $itemId)->delete();
            
            Db::commit();
            return JsonResponse::success([], '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 获取字典项详情
     * @permission system:dictItem:getInfo
     */
    public function getInfo()
    {
        $itemId = Request::param('item_id');
        
        $dictItem = DictItemModel::with(['langs'])->find($itemId);
        if (!$dictItem) {
            return JsonResponse::error('字典项不存在');
        }
        
        return JsonResponse::success([
            'info' => $dictItem
        ]);
    }
} 